<?php

namespace app\admin\controller;

use app\admin\model\AdminLog;
use app\common\controller\Backend;
use think\Config;
use think\Hook;
use think\Validate;
use fast\Random;
use think\Session;
use think\Exception;
use think\Db;
use app\common\model\User;

/**
 * 后台首页
 * @internal
 */
class Index extends Backend
{
    protected $noNeedLogin = ['login', 'register'];
    protected $noNeedRight = ['index', 'logout'];
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 后台首页
     */
    public function index()
    {
        //
        $menulist = $this->auth->getSidebar([
            // 'dashboard' => 'hot',
            // 'addon'     => ['new', 'red', 'badge'],
            // 'auth/rule' => 'side',
            // 'general'   => ['new', 'purple'],
                ], $this->view->site['fixedpage']);
        $this->view->assign('menulist', $menulist);
        $this->view->assign('title', __('Home'));
        return $this->view->fetch();
    }

    /**
     * 管理员登录
     */
    public function login()
    {
        $url = $this->request->get('url', 'index/index');
        if ($this->auth->isLogin())
        {
            $this->error(__("You've logged in, do not login again"), $url);
        }
        if ($this->request->isPost())
        {
            $username = $this->request->post('username');
            $password = $this->request->post('password');
            $keeplogin = $this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:3,30',
                '__token__' => 'token',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                '__token__' => $token,
            ];
            if (Config::get('uctoo.login_captcha'))
            {
                $rule['captcha'] = 'require|captcha';
                $data['captcha'] = $this->request->post('captcha');
            }
            $validate = new Validate($rule, [], ['username' => __('Username'), 'password' => __('Password'), 'captcha' => __('Captcha')]);
            $result = $validate->check($data);
            if (!$result)
            {
                $this->error($validate->getError(), $url, ['token' => $this->request->token()]);
            }
            AdminLog::setTitle(__('Login'));
            $result = $this->auth->login($username, $password, $keeplogin ? 86400 : 0);
            if ($result === true)
            {
                $this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $username, 'avatar' => $this->auth->avatar]);
            }
            else
            {
                $this->error(__('Username or password is incorrect'), $url, ['token' => $this->request->token()]);
            }
        }

        // 根据客户端的cookie,判断是否可以自动登录
        if ($this->auth->autologin())
        {
            $this->redirect($url);
        }
        $background = cdnurl(Config::get('uctoo.login_background'));
        $this->view->assign('background', $background);

        //微信扫码登录
        //查询配置了微信登录的网站型应用
        $map['admin_id'] = 1;
        $map['business_info'] = '{"wxlogin":1}';  //TODO:支持多个配置参数选出wxlogin配置项的查找
        $appinfo = model ( 'wechat_applet' )->where ( $map )->find ();
        trace($appinfo,'appinfo：');
        $this->assign('appid', $appinfo['appid']);
        $redirect_uri = httpTohttps(url('mpopen/mpopen/wxlogin_callback',['appletid' => $appinfo['appletid']],false,true));
        trace($redirect_uri,'$redirect_uri：');
        $this->assign('redirect_uri', urlencode($redirect_uri));
        $state = time();
        trace($state,'$state：');
        session('wxlogin_state', $state);   //保存state到session用于回调时验证
        $this->assign('state', $state);

        $this->assign('login_type', '');


        Hook::listen("login_init", $this->request);
        return $this->view->fetch();
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'), 'index/login');
    }

    /**
     * 管理员注册，只支持微信扫码登录注册
     */
    public function register()
    {
        $url = $this->request->get('url', 'index/index');
        trace($url,'register$url：');
        trace(Session::has('user_info'),'register$user_info：');
        if(!Session::has('user_info'))
        {
            $this->error(__('Login using scan qrcode wechat'));
        }
        //Session::get('applet_info.appletid');
        $model = model('Admin');
        if ($this->request->isPost())
        {
            $params = input('param.');
            trace($params,'register$params：');
            if ($params)
            {
                //账号注册时需要开启事务,避免出现垃圾数据
                Db::startTrans();
                try {
                    $params['salt'] = Random::alnum();
                    $password = $params['password'];
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                    $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
                    $params['nickname'] = $params['username'];
                    $params['email'] = $params['username'].'@uctoo.com';
                    $result = $model->validate('Admin.add')->save($params);
                trace($result,'register$result：');
                    if ($result === false) {
                        $this->error($model->getError());
                    }
                    $map['name'] = '注册会员';                     //名字必须起成'注册会员'
                    $value = model('AuthGroup')->where($map)->find();
                    $dataset[] = ['uid' => $model->id, 'group_id' => $value['id']];
                    model('AuthGroupAccess')->saveAll($dataset);
                trace($dataset,'register$AuthGroupAccess：');
                    //创建微信端帐号
                    $user = new User;

                    $user->uid = $model->id;              //微信端帐号uid与会员id关联
                    $user->mp_id = Session::get('user_info.mp_id');
                    $user->openid = Session::get('user_info.openid');
                    $username = $user->username = $params['username'];
                    $user->nickname = Session::get('user_info.nickname');
                    $user->mobile = $params['username'];                 //注册默认用手机号码作为用户名
                    $user->gender = Session::get('user_info.sex');
                    $user->birthday = '1980-01-01';
                    $user->province = Session::get('user_info.province');
                    $user->city = Session::get('user_info.city');
                    $user->country = Session::get('user_info.country');
                    $user->salt = Random::alnum();
                    $user->avatar = Session::get('user_info.headimgurl');
                    $user->privilege = json_encode(Session::get('user_info.privilege'));
                    $user->union_id = Session::get('user_info.unionid');
                    $user->status = 'normal';
                    $user->loginip = request()->ip();
                    $user->joinip = request()->ip();
                    $user->prevtime = time();
                    $user->jointime = time();
                    $user->access_token = Session::get('user_info.access_token');
                    $user->access_token_overtime = Session::get('user_info.access_token_overtime');
                    $user->refresh_token = Session::get('user_info.refresh_token');
                    $user->save();
                trace($user,'register$user：');

                    Db::commit();
                }
                catch (Exception $e)
                {
                    Db::rollback();
                    $this->error($e->getMessage(), $url, ['token' => $this->request->token()]);
                }
                //登录帐号

                $result = $this->auth->login($username, $password, 0);
                trace($result,'registerlogin$result：');
                AdminLog::setTitle(__('Login'));
                if ($result === true)
                {
                    $this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $username, 'avatar' => $this->auth->avatar]);
                }
                else
                {
                    $this->error(__('Username or password is incorrect'), $url, ['token' => $this->request->token()]);
                }
            }
            $this->error();
        }

        $background = cdnurl(Config::get('uctoo.login_background'));
        $this->view->assign('background', $background);
        return $this->view->fetch();
    }

}